#!/usr/bin/env python
import calendar
import random
import sqlite3
import sys
import time,datetime
import threading
from kisp import *
from sensors import *

db_file = 'invigilator.db'

class PollThread(threading.Thread):
	def __init__(self, id,minutes,sensor,arguments,state):
		threading.Thread.__init__(self)
		self.id = id
		self.minutes = minutes
		self.sensor = sensor
		self.arguments = arguments.split("\31")
		self.state = state 
		
	def run(self):
		db = sqlite3.connect(db_file,isolation_level=None)
		sql = db.cursor()
		sql.execute('DELETE FROM poll_schedule WHERE POLL_ID=?',[self.id])
		next_poll_time = datetime.datetime.now() + datetime.timedelta(minutes=self.minutes)

		for sensor in KISP.plugins:
			if sensor.Name == self.sensor and sensor.Type == "Sensor":
				result=sensor().Start(self.arguments)
				ut_now=calendar.timegm(datetime.datetime.now().timetuple())
				
				sql.execute('INSERT INTO rrdb (TIME, POLL_ID, STATE, VALUE, DESCRIPTION) VALUES ( ?, ?, ?, ?, ? )', (ut_now, self.id, result[0], result[1], result[2]))
				sql.execute('UPDATE polls SET STATE=? WHERE ID=?',( result[0],self.id))
				sql.execute('INSERT INTO poll_schedule (POLL_ID, TIME) VALUES (?, ?)', (self.id, next_poll_time))
				sql.execute('DELETE FROM RRDB WHERE POLL_ID=? AND TIME NOT IN (SELECT TIME FROM RRDB WHERE POLL_ID=? ORDER BY TIME DESC LIMIT ?)',(self.id,self.id,120))
				
				if int(result[0]) != self.state:
					sql.execute('SELECT ID FROM TAGS WHERE POLL_ID=?',[self.id])
					sql2 = db.cursor()
					sql3 = db.cursor()
					
					for tag_id in sql:
						if int(result[0]) != 0:
							event_id = hex(hash(random.random()))[2:]
							sql2.execute('INSERT INTO EVENTS (ID, TAG_ID, POLL_ID, TIME, STATUS) VALUES ( ?, ?, ?, ?, ? )', (event_id,tag_id[0],self.id,ut_now,"NEW"))
							sql2.execute('SELECT ID, TIMING FROM TRIGGERS WHERE TAG_ID=?', [tag_id[0]])
							for trigger in sql2:
								sql3.execute("INSERT INTO TRIGGER_SCHEDULE (ID, EVENT_ID, TIME) VALUES (?,?,?)",(trigger[0],event_id,datetime.datetime.now() + datetime.timedelta(minutes=trigger[1])))
						else:
							sql2.execute('UPDATE EVENTS SET STATUS="RESOLVED" WHERE TAG_ID=? AND POLL_ID=?', (tag_id[0],self.id))
				sql.close
				break

def main():	
	db = sqlite3.connect(db_file,isolation_level=None)
   	sql = db.cursor()
	sql.execute("create table IF NOT EXISTS rrdb (TIME TIMESTAMP , POLL_ID text, STATE real, VALUE real, DESCRIPTION text)")
   	sql.execute("create table IF NOT EXISTS polls(ID text, TITLE text, MINUTES real, SENSOR text, ARGUMENTS text, STATE real)")
	sql.execute("create table IF NOT EXISTS poll_schedule(POLL_ID text, TIME TIMESTAMP)")
	sql.execute("create table IF NOT EXISTS tags(ID text, POLL_ID text)")
	sql.execute("create table IF NOT EXISTS tag_descriptions(ID text, TITLE text, DESCRIPTION text)")
	sql.execute("create table IF NOT EXISTS events(ID text, TAG_ID text, POLL_ID text, TIME TIMESTAMP, STATUS text)")
	sql.execute("create table IF NOT EXISTS triggers(ID text, TAG_ID text, DESCRIPTION text, ACTION text, ARGUMENTS text, TIMING real)")	
	sql.execute("create table IF NOT EXISTS trigger_schedule(ID text, EVENT_ID text, TIME TIMESTAMP)")
	
	sql.execute("select POLLS.ID, POLLS.MINUTES, POLLS.SENSOR, POLLS.ARGUMENTS, POLLS.STATE from polls,poll_schedule WHERE POLLS.ID = POLL_SCHEDULE.POLL_ID AND POLL_SCHEDULE.TIME < ?",[datetime.datetime.now()])
	for row in sql:
		PollThread(row[0],row[1],row[2],row[3],row[4]).start()
	sql.close

if __name__ == "__main__":
	main()
 